package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单管理
 */
@Controller
public class OrderController {

    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private OrderFeignClient orderFeignClient;


    //去结算
    @GetMapping("/trade.html")
    public String trade(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1:查询收货地址集合   来源于 用户微服务（认证微服务）
        List<UserAddress> userAddressList = userFeignClient.
                findUserAddressListByUserId(Long.parseLong(userId));
        request.setAttribute("userAddressList",userAddressList);
        //2:查询商品清单      来源来 购物车微服务   orderDetail
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(Long.parseLong(userId));
        List<OrderDetail> orderDetailList = cartCheckedList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            //将购物车中数据转移到订单详情对象中来
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            return orderDetail;
        }).collect(Collectors.toList());
        request.setAttribute("detailArrayList",orderDetailList);
        //3:商品件数
        long totalNum = orderDetailList.stream().collect(
                Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
        request.setAttribute("totalNum",totalNum);
        //、商品总金额（计算出来的）
        double totalAmount = orderDetailList.stream().collect(Collectors.summarizingDouble((orderDetail) -> {
            return orderDetail.getOrderPrice().doubleValue() * orderDetail.getSkuNum();
        })).getSum();
        request.setAttribute("totalAmount",totalAmount);
        //4:交易号  生成交易号
        String tradeNo = orderFeignClient.tradeNo();
        request.setAttribute("tradeNo",tradeNo);
        return "order/trade";
    }
}
